<template>
  <view class='container'>
    <!-- ------------------------ 顶logo**start ------------------------ -->
    <view class="logo-top">
      <!-- <image class="img" :src="logoImg" mode="aspectFill"></image> -->
      <image class="img" :src="`${baseUrl}/images/brand/${groupInfo[1].logoUlr}`" mode="aspectFill"></image>
    </view>
    <!-- ------------------------ 顶banner**start ------------------------ -->
    <view class="banner-top">
      <image class="img" src="http://www.kamlung.net:3520/images/zeekr/other/reservation.jpg" mode="aspectFill"></image>
    </view>
    <view class="address-btn__ware">
      <view class="address-item" v-for='item in companyList' :key='item.idc'>
        <view class="title-box">
          <view class="title">{{ item.markers_title }}</view>
          <view class="nav-box" @click="goStore(item, item.idc)">
            <view class="nav">導航到店</view>
            <uni-icons color="#c70025" type="paperplane" size="18"></uni-icons>
          </view>
        </view>
        <view><text class="name">營業時間：</text>{{ item.time }}</view>
        <view v-if="item.sale_hotline != '' || item.after_sales_hotline != ''"><text class="name"> 查詢：</text>{{
        item.sale_hotline == '' ? item.after_sales_hotline : item.sale_hotline }}
        </view>
        <view class="address"><text class="name">地址：</text> {{ item.markers_address }}</view>
      </view>
    </view>
    <!-- ------------------------ 表单**start ------------------------ -->
    <view class="form_box">
      <uni-forms border ref="testDrivFormRef" :rules="rules" label-width="80px" :modelValue="testDriveaParam"
        label-align="right">
        <uni-forms-item label="現有車型">
          <uni-easyinput maxlength="12" placeholder="請輸入現有車型" v-model="testDriveaParam.curr_car_model"
            :inputBorder="false" />
        </uni-forms-item>
        <!-- <picker :value="value" range-key="value" :range="carSeris" @change="carsChange"> -->
        <uni-forms-item label="車 型" required name="car_model">
          <view class="my-input-box" @click="clickShowCartModel">
            <view class="my-input" v-if="testDriveaParam.car_model.length">{{
        testDriveaParam.car_model
      }}</view>
            <view v-else class="my-input placehol">請選擇车型</view>
            <uni-icons class="icon" color="#999" type="bottom" size="40rpx"></uni-icons>
          </view>
        </uni-forms-item>
        <!-- </picker> -->
        <uni-forms-item label="姓 名" required name="name">
          <uni-easyinput maxlength="10" placeholder="請輸入姓名" :inputBorder="false" v-model="testDriveaParam.name" />
        </uni-forms-item>
        <uni-forms-item label="聯絡方式" required name="contactWay">
          <view class="my-input-box" @click="clickContactWayModel">
            <view class="my-input" v-if="testDriveaParam.contactWay.length">{{
        testDriveaParam.contactWay
      }}</view>
            <view v-else class="my-input placehol">請選擇聯絡方式</view>
            <uni-icons class="icon" color="#999" type="bottom" size="40rpx"></uni-icons>
          </view>
        </uni-forms-item>
        <uni-forms-item label="電話號碼" required name="phone_no">
          <view class="phone_no">
            <view style="margin-right: 10rpx;" v-if="isHKAndMacao">{{ photoPrefix }}</view>
            <uni-easyinput maxlength="11" type="number" placeholder="請輸入電話號碼" :inputBorder="false"
              v-model="testDriveaParam.phone_no" />
          </view>
        </uni-forms-item>

        <uni-forms-item label="門 店" required name="company">
          <view class="my-input-box" @click="clickShowAddressList">
            <view class="my-input" v-if="testDriveaParam.company.length">{{
        testDriveaParam.company
      }}</view>
            <view v-else class="my-input placehol">请選擇門店</view>
            <uni-icons class="icon" color="#999" type="bottom" size="40rpx"></uni-icons>
          </view>
        </uni-forms-item>
        <uni-forms-item label="電 郵" required name="email">
          <uni-easyinput maxlength="18" placeholder="請輸入電郵" :inputBorder="false" v-model="testDriveaParam.email" />
        </uni-forms-item>
        <uni-forms-item label="其 它">
          <uni-easyinput maxlength="150" autoHeight type="textarea" placeholder="請輸入其它"
            v-model="testDriveaParam.remark_box">
          </uni-easyinput>
        </uni-forms-item>
      </uni-forms>
    </view>
    <!-- ------------------------ 底盒子**start ------------------------ -->
    <view class="bottom-box">
      <view class="radio_box" style="margin: 0 0 20rpx 0;">
        <u-checkbox-group>
          <u-checkbox activeColor="#de4141" :checked="checkedVal" @change="change">
          </u-checkbox>
        </u-checkbox-group>
        <view>
          我已閱讀，理解並同意<text @click="$refs.ruleHK.openRul()" class="policy">私隱政策</text>，包括個人資料收集聲明。</view>
      </view>
      <view class="radio_box">
        <u-checkbox-group>
          <u-checkbox activeColor="#de4141" :checked="pushMsg" @change="pushMsgChange">
          </u-checkbox>
        </u-checkbox-group>
        <view>
          我不希望收到錦龍汽車集團的直接促銷。</view>
      </view>
      <view class="sub-btn" color="#de4141" @click="submit">提 交</view>
    </view>
    <!-- ------------------------ 选择聯系方式**start ------------------------ -->
    <u-picker :immediateChange="true" :show="contactWayModel" :columns="contactWaySelect" :closeOnClickOverlay="true"
      title="請選擇聯絡方式" @close="contactWayModel = false" @confirm="selectContactWay" @cancel="contactWayModel = false">
    </u-picker>
    <!-- ------------------------ 选择车型**start ------------------------ -->
    <u-picker :immediateChange="true" :show="showCartModel" :columns="carModelList" :closeOnClickOverlay="true"
      title="請選擇车型" @close="showCartModel = false" @confirm="selectSowCartModel" @cancel="showCartModel = false">
    </u-picker>
    <!-- ------------------------ 选择地区**start ------------------------ -->
    <u-picker :immediateChange="true" :show="showAddressList" :columns="addressList" :closeOnClickOverlay="true"
      title="請選擇門店" @close="showAddressList = false" @confirm="selectAddress" @cancel="showAddressList = false"
      keyName="name">
    </u-picker>
    <!-- 政策组件 -->
    <RulesCompany ref="rule"></RulesCompany>
    <!-- 香港政策组件 -->
    <RulesCompanyHK ref="ruleHK"></RulesCompanyHK>
  </view>
</template>
<script>

import { mapState } from 'vuex'
import { cloneDeep } from 'lodash'
import { carModelListApi } from '@/API/carSeries'
import { companyListApi } from '@/API/reqData'
import { rulesTestDrive } from '@/static/js/rules'
import { addTestDrive, testDrive } from '@/API/testDrive'
import { getOpenIdApi, sendMessageApi } from '@/API/home'
import { brand, brand_id, tmplIds, logoImg, } from '@/static/js/staticData'
// import ApeEditor from '@/components/ApeEditor' 
export default {
  name: 'MyInfo',
  data() {
    return {
      logoImg,
      contactWayModel: false,
      contactWaySelect: [['中國香港', '中國澳門', '中國內地']],
      companyList: [],
      baseUrl: this.$baseUrl,
      // 基础表单数据
      testDriveaParam: {
        type: 'A',
        name: '',
        phone_no: '',
        address: '',
        curr_car_model: '',
        car_age: '',
        car_model: '',
        industry: '',
        company: '',
        company_id: '',
        brand_id,
        uuid: '',
        // -----
        email: '',//邮件
        promotion: '', //是否推广 // 推送消息
        remark_box: '',//备注
        visit_time: '', //到访时间
        // -----------
        way: '',
        contactWay: '',
      },
      rules: {},
      carModelList: [[]],
      checkedVal: false,
      showCartModel: false,
      showAddressList: false,
      testDrive: {
        brand_id,
        userInfo: {
          touser: '',
          page: 'pages/TestDrive/MyTestDrive',
          template_id: '',
          data: {}
        }
      },
    }
  },
  mounted() {
    // 车型列表
    this.carModelListFn()
    this.companyListFn()
    // setTimeout(() => {
    //   console.log('blur :>> ');
    //   console.log('this.$refs.easyinput', this.$refs.easyinput)
    //   this.$refs.easyinput.focus()
    // }, 6000)
  },
  methods: {
    async companyListFn() {
      const {
        data: { code, data }
      } = await companyListApi({ state: 1, brand_id: 52 })
      if (code == 200) {
        // console.log('data :>> ', data);
        data.forEach((item, index1) => {
          item.company_list.forEach((item, index2) => {
            item.idc = index1 + '' + index2
            if (index1 == 0) item.time = '09:00 - 20:00'
            if (index1 == 1) item.time = '10:00 - 20:00'
          })
          this.companyList.push(...item.company_list)
        })
        // console.log('this.companyList :>> ', this.companyList);
        // this.companyList = data
      }
    },
    // ------------------------ 车型列表**start ------------------------
    async carModelListFn() {
      const {
        data: { code, data }
      } = await carModelListApi({ company_type: 3, brand_id: 52 })
      if (code == 200) {
        // console.log('data :>> ', data);
        let temp = []
        for (let i = 0; i < data.length; i++) {
          for (let j = 0; j < data[i].ve_groups.length; j++) {
            if (data[i].ve_name != '001 FR') {
              temp.push(data[i].ve_groups[j].vem_name)
            }
          }
        }
        // let temp = data.map(item => item.ve_name)
        console.log('temp :>> ', temp);
        this.carModelList = [temp]
      }
    },
    // 导航到店
    goStore(e, i) {
      console.log('e', e, i)
      let { markers_title, markers_address, latitude, longitude } = e
      uni.openLocation({
        name: markers_title,
        address: markers_address,
        latitude: parseFloat(latitude),
        longitude: parseFloat(longitude),
      })
    },
    clickShowCartModel() {
      this.showCartModel = true
      let interval = setInterval(function () {
        uni.hideKeyboard(); //隐藏软键盘
        console.log('隐藏软键盘 :>> ')
      }, 10);
      setTimeout(() => {
        clearInterval(interval);
      }, 800);
    },
    clickContactWayModel() {
      this.contactWayModel = true
      let interval = setInterval(function () {
        uni.hideKeyboard(); //隐藏软键盘
        console.log('隐藏软键盘 :>> ')
      }, 10);
      setTimeout(() => {
        clearInterval(interval);
      }, 800);
    },
    clickShowAddressList() {
      this.showAddressList = true
      let interval = setInterval(function () {
        uni.hideKeyboard(); //隐藏软键盘
        console.log('隐藏软键盘 :>> ')
      }, 10);
      setTimeout(() => {
        clearInterval(interval);
      }, 800);
    },
    // 聯系方式
    selectContactWay(e) {
      this.testDriveaParam.contactWay = e.value[0]
      this.contactWayModel = false
    },
    // 车型
    selectSowCartModel(e) {
      this.testDriveaParam.car_model = e.value[0]
      this.showCartModel = false
    },
    //選擇地區
    selectAddress(e) {
      this.testDriveaParam.company_id = e.value[0].id
      this.testDriveaParam.company = e.value[0].name
      this.showAddressList = false
    },
    // 调用子组件方法
    openRules() {
      this.$refs.rule.openRul()
    },
    change(e) {
      this.checkedVal = e
    },
    pushMsgChange(e) {
      this.testDriveaParam.promotion = e
    },
    submit() {
      console.log('testDriveaParam :>> ', this.testDriveaParam);
      if (!this.checkedVal) {
        return uni.$showMsg('请阅读并同意勾选登录协议')
      }
      this.$refs.testDrivFormRef.validate().then(async (res) => {
        // console.log('this.$refs :>> ', this.$refs.testDrivFormRef);
        let temp = cloneDeep(this.testDriveaParam)
        temp.phone_no = `${this.photoPrefix}${temp.phone_no}`
        console.log('res -通过了6:>> ', temp);
        // uni.showToast({
        //   title: '预约成功!',
        //   icon: 'success',
        //   mask: true,
        // })

        let { uuid } = this.loginInfo
        temp.uuid = uuid
        const {
          data: { code },
        } = await addTestDrive(temp)
        if (code === 200) {
          uni.showToast({
            title: '预约成功!',
            icon: 'success',
            mask: true,
          })
          this.checkedVal = false
          this.$refs.testDrivFormRef.clearValidate()

          let { testDrivea, maintain } = tmplIds // 模板ID
          if (temp.type == 'A') {
            this.testDrive.userInfo.data = { //该品牌新创了模板
              thing11: {
                value: temp.name,
              },
              phone_number2: {
                value: temp.phone_no,
              },
              thing1: {
                value: temp.car_model,
              },
              thing7: {
                value: temp.company,
              },
              thing8: {
                value: '預約成功！ 等待客服電話聯系確認試駕時間。',
              },
            }

            this.testDriveaParam = {// 试驾预约
              type: 'A',
              name: '',
              phone_no: '',
              address: '',
              curr_car_model: '',
              car_age: '',
              car_model: '',
              industry: '',
              company: '',
              company_id: '',
              brand_id,
              uuid: '',
              // -----
              email: '',//邮件
              promotion: '', //是否推广 // 推送消息
              remark_box: '',//备注
              visit_time: '', //到访时间
              // -----------
              way: '',
              contactWay: '',
            }

            // uni.requestSubscribeMessage({
            //   //模板的模板ID
            //   tmplIds: [testDrivea],
            //   success: (res) => {

            //     if (res[testDrivea] == 'accept') {
            //       //  用户同意发送信息时
            //       // 调用oppeId,api
            //       this.getUserOpenid()
            //     } else {
            //       //  用户不同意发送信息时
            //       // uni.$showMsg('授权失败')
            //       uni.navigateTo({
            //         url: '/pages/TestDrive/MyTestDrive',
            //       })
            //     }
            //   },
            //   fail: (err) => {
            //     //  用户选择一直不要发送信息时
            //     uni.navigateTo({
            //       url: '/pages/TestDrive/MyTestDrive',
            //     })
            //   },

            // })

            console.log('object666 :>> ',);
          }
        }
      }).catch((errors) => {
        console.log('errors', errors)
        // uni.$u.toast('请输入完整数据！')
      })
    },
    // 获取openId
    async getUserOpenid() {
      const [err, res] = await uni.login().catch((err) => err)
      if (err || res.errMsg !== 'login:ok')
        return uni.$showMsg('获取code失败！')
      const {
        data: { data, code },
      } = await getOpenIdApi({ brand, code: res.code })
      if (code === 200) {
        // 获取oppeId成功，调用发关送信息api
        // 调用试驾发送信息
        this.sendTestDrive(data.uuid)
      }
    },
    // 试驾发送信息
    async sendTestDrive(oppeId) {
      this.testDrive.userInfo.touser = oppeId
      const { data } = await sendMessageApi(this.testDrive)
      if (data.code === 200) {
        uni.navigateTo({
          url: '/pages/TestDrive/MyTestDrive',
        })
      }
    },
  },
  computed: {
    ...mapState(['loginInfo', 'centers', 'groupInfo']),
    addressList() {
      let temp = this.centers.map(item => ({ id: item.id, name: item.text }))
      return [temp]
    },
    // 是香港或澳门
    isHKAndMacao() {
      let { contactWay } = this.testDriveaParam
      // return company == '宾利-澳门' || company == '宾利-香港'
      return contactWay.indexOf('香港') > -1 || contactWay.indexOf('澳門') > -1
    },
    // 是香港
    photoPrefix() {
      let { contactWay } = this.testDriveaParam
      if (contactWay.indexOf('港') > -1) {
        return "+852"
      }
      if (contactWay.indexOf('澳') > -1) {
        return "+853"
      }
      return ''
    }
  },
  watch: {
    // loginInfo: {
    //   handler(newVal = {}) {
    //     if (Object.keys(newVal).length === 0) return false    // 是否已登录
    //     if (Object.keys(this.latLog).length === 0) {// 是否已获取定位
    //       this.getLocation()
    //     }
    //   },
    //   immediate: true
    // },
    isHKAndMacao: {
      handler(newVal) {
        this.rules = rulesTestDrive(newVal)
      },
      immediate: true
    },
  }
}
</script>
<style scoped>
/* ::v-deep .form_box .form_box_form-item1>view { */
/* background: green; */
/* position: relative; */
/* } */
</style>
<style lang='scss' scoped>
::v-deep .form_box .form_box_form-item1>view {
  /* background: green; */
  position: relative;
}

.eeee {
  position: absolute;
  left: -6px;
  top: 14px;
  font-size: 20px;
  color: #f56c6c;

}

.ffff {
  position: absolute;
  left: 16px;
  top: 14px;
  font-size: 20px;
  color: #f56c6c;
}

.padding-l-r-30 {
  padding-left: 30rpx;
  padding-right: 30rpx;
}

.margin-l-r-30 {
  margin-left: 30rpx;
  margin-right: 30rpx;
}

.container {
  padding-bottom: 50rpx;

  // ------------------------ 顶logo**start ------------------------
  .logo-top {
    width: 400rpx;
    height: 180rpx;
    margin: 0 auto;
  }

  // ------------------------ 顶banner**start ------------------------
  .banner-top {
    width: 100%;
    height: 66.66vw;
  }

  .address-btn__ware {
    padding-top: 30rpx;
    padding-bottom: 20rpx;
    padding-left: 60rpx;
    padding-right: 60rpx;
    background-color: rgba(241, 239, 235);
    // padding-left: 45rpx;
    // padding-right: 45rpx;

    .address-item {
      font-size: 26rpx;
      margin-bottom: 30rpx;

      .title-box {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .title {
          font-size: 28rpx;
          line-height: 60rpx;
          font-weight: 600;
        }

        .nav-box {
          width: 136rpx;
          display: flex;
          justify-content: space-between;
          align-items: center;

          .nav {
            font-size: 24rpx;
            color: #c70025;
          }
        }
      }


      .name {
        font-weight: 600;
      }

      .address {
        margin-bottom: 10rpx;
      }
    }

    // .address-item:nth-child(n+2) {
    //   margin-top: 30rpx;
    // }
  }



  // ------------------------ 表单**start ------------------------
  .form_box {
    padding-left: 60rpx;
    padding-right: 60rpx;

    .remark-ware {
      margin-top: 30rpx;
      margin-bottom: 30rpx;
      display: flex;
      justify-content: space-between;
      align-items: flex-start;

      .remark {
        width: 68px;
        margin-right: 30rpx;
        color: #303133;
        font-size: 15px;
        text-align: right;
      }
    }
  }

  // ------------------------ 底盒子**start ------------------------
  .bottom-box {
    // width: 100%;
    // padding: 20rpx;
    // margin-top: -200rpx;
    // padding-bottom: 100rpx;
    padding-left: 60rpx;
    padding-right: 60rpx;

    .radio_box {
      font-size: 26rpx;
      margin-bottom: 30rpx;
      // padding: 0 20rpx;
      display: flex;

      .policy {
        color: $theme-color;
        text-decoration: underline double;
      }
    }

    // 提交按钮
    .sub-btn {
      width: calc(100% - 20rpx);
      margin: 0 10rpx;
      border-radius: 6rpx;
      font-size: 32rpx;
      line-height: 88rpx;
      text-align: center;
      color: white;
      background-color: #c70025;
    }
  }
}

.radio_box {
  margin-bottom: 30rpx;
  padding: 0px 14rpx;
  // text-align: center;
  display: flex;
  justify-content: start;

  .policy {
    color: $theme-color;
  }
}

.my-input-box {
  position: relative;

  .my-input {
    padding: 2px 10px 0 10px;
    font-size: 14px;
    color: #666;
    // border-bottom: 1px solid #ddd;
    line-height: 36px;
    height: 36px;
    @include text-ellipsis();
  }

  .placehol {
    color: #999 !important;
    font-size: 12px !important;
  }

  .icon {
    position: absolute;
    top: 12rpx;
    right: 5rpx;
  }
}

.phone_no {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>